package cc.rengu.igas.share.core.service.channel.upgw;

import cc.rengu.igas.channel.upgw.facade.base.Header;
import cc.rengu.igas.channel.upgw.facade.bean.ReceiveInfo;
import cc.rengu.igas.channel.upgw.facade.bean.RiskInfo;
import cc.rengu.igas.channel.upgw.facade.request.UpgwEnterpriseGatewayTransStateQueryRequest;
import cc.rengu.igas.channel.upgw.facade.response.UpgwEnterpriseGatewayTransStateQueryResponse;
import cc.rengu.igas.channel.upgw.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.*;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * UPGW-银联网关支付-企业网关交易状态查询
 * Created by lzl on 2021/4/23 11:08
 */
public class UpgwEnterpriseGatewayTransStateQueryService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header upgwHeader = new Header();
        upgwHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        upgwHeader.setChanlId(channelCallCfg.getMsgSrcId());
        upgwHeader.setSrcSysId(AppParamConstant.SYS_ID);
        upgwHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        upgwHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        upgwHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        upgwHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        upgwHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        upgwHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        UpgwEnterpriseGatewayTransStateQueryRequest queryRequest = new UpgwEnterpriseGatewayTransStateQueryRequest();
        queryRequest.setHeader(upgwHeader);
        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(upgwHeader.getInstId(), xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO));
        if (null == mchntInfo) {
            rglog.error("获取商户信息失败,mchntNo:<{}>", orderInfo.getMchntOrderInfoList().get(0).getMchntNo());
            return null;
        }
        Predicate<PayOrderInfo> channelFilter = p -> channelCallCfg.getCallChannelId().equals(p.getMsgDstId());
        List<PayOrderInfo> payOrderInfoList = orderInfo.getPayOrderInfoList().stream().filter(channelFilter).collect(Collectors.toList());
        queryRequest.setOrigTraceNo(Objects.requireNonNull(payOrderInfoList.get(0)).getChannelReconKey());
        queryRequest.setOrigTransDate(payOrderInfoList.get(0).getTxnDate());
        /*获取银联机构号*/
        SysParamService sysParamService = new SysParamServiceImpl();
        SysParam ncqsInstCodeParam = sysParamService.getSysParamInfo(upgwHeader.getInstId(), "OPMS_SYS_PARAM", "NCQS_INST_CODE");
        queryRequest.setOriIssrId((null != ncqsInstCodeParam) ? ncqsInstCodeParam.getParamValue() : mchntInfo.getCupsInstId());
        queryRequest.setOrigRecvAcctInfo("");
        queryRequest.setRecvSignNo("");
        ReceiveInfo receiveInfo = new ReceiveInfo();
        receiveInfo.setDevId("");
        receiveInfo.setIpAddr("");
        receiveInfo.setMacAddr("");
        queryRequest.setReceiveInfo(receiveInfo);
        RiskInfo riskInfo = new RiskInfo();
        ConvertUtil.convertOutput(riskInfo);
        queryRequest.setRiskInfo(riskInfo);
        rglog.debug("UPGW 银联网关支付-企业网关交易状态查询请求:<{}>", JSON.toJSONString(queryRequest));
        return queryRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        //此交易不登记支付订单
        return null;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        UpgwEnterpriseGatewayTransStateQueryRequest queryRequest = (UpgwEnterpriseGatewayTransStateQueryRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<UpgwEnterpriseGatewayTransStateQueryResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPGW_PAY_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.UPGW_ENTERPRISE_GATEWAY_TRANS_STATE_QUERY_METHOD, queryRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.UPGW_PAY_SERVICE, ShareServiceConstant.UPGW_ENTERPRISE_GATEWAY_TRANS_STATE_QUERY_METHOD, queryRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.UPGW_PAY_SERVICE_INNER_PATH);
                callResult = (Result<UpgwEnterpriseGatewayTransStateQueryResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.UPGW_ENTERPRISE_GATEWAY_TRANS_STATE_QUERY_METHOD, queryRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<UpgwEnterpriseGatewayTransStateQueryResponse>) dubboService.callDubboService(ShareServiceConstant.UPGW_PAY_SERVICE, ShareServiceConstant.UPGW_ENTERPRISE_GATEWAY_TRANS_STATE_QUERY_METHOD, queryRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<UpgwEnterpriseGatewayTransStateQueryResponse> callResult = (Result<UpgwEnterpriseGatewayTransStateQueryResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getDstCallIndex().equals(payOrderIndex)).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            UserOrderInfo userOrderInfo = orderInfo.getUserOrderInfo();
            List<MchntOrderInfo> mchntOrderInfoList = orderInfo.getMchntOrderInfoList();
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            UpgwEnterpriseGatewayTransStateQueryResponse upgwEnterpriseGatewayTransStateQueryResponse = callResult.getResult();
            if (TransStatusEnum.TRANS_SUCC.equals(transStatusEnum)) {
                if ("1".equals(upgwEnterpriseGatewayTransStateQueryResponse.getOrigTxnResultInfo().getOrigTxnStatus())) {
                    /* 更新当前用户订单信息 */
                    userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                    userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                    userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    userOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    /* 更新当前商户订单信息 */
                    for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                        mchntOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                        mchntOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                        mchntOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    }
                    /* 更新当前支付订单信息 */
                    payOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
                    payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
                    List<PayOrderInfo> payOrderInfoList = new ArrayList<>();
                    payOrderInfoList.add(payOrderInfo);
                    updateOrderInfo.setUserOrderInfo(userOrderInfo);
                    updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                    updateOrderInfo.setPayOrderInfoList(payOrderInfoList);
                } else if ("2".equals(upgwEnterpriseGatewayTransStateQueryResponse.getOrigTxnResultInfo().getOrigTxnStatus())) {
                    rglog.debug("原订单正在处理中，不做任务处理!");
                } else {
                    /* 更新用户订单信息 */
                    String currentDateTime = DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS");
                    userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
                    userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                    userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    userOrderInfo.setUpdateTime(currentDateTime);
                    /* 更新商户订单信息 */
                    for (MchntOrderInfo mchntOrderInfo : mchntOrderInfoList) {
                        mchntOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                        mchntOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                        mchntOrderInfo.setUpdateTime(currentDateTime);
                    }
                    /* 更新支付订单信息 */
                    payOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
                    payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    payOrderInfo.setSettleDate(upgwEnterpriseGatewayTransStateQueryResponse.getOrigTxnResultInfo().getOrigSettleDate());
                    payOrderInfo.setRespCode(upgwEnterpriseGatewayTransStateQueryResponse.getOrigTxnResultInfo().getOrigRespCode());
                    payOrderInfo.setRespDesc(upgwEnterpriseGatewayTransStateQueryResponse.getOrigTxnResultInfo().getOrigRespDesc());
                    payOrderInfo.setUpdateTime(currentDateTime);
                    List<PayOrderInfo> payOrderInfoList = new ArrayList<>();
                    payOrderInfoList.add(payOrderInfo);
                    updateOrderInfo.setUserOrderInfo(userOrderInfo);
                    updateOrderInfo.setMchntOrderInfoList(mchntOrderInfoList);
                    updateOrderInfo.setPayOrderInfoList(payOrderInfoList);
                }
            }
        }
        return updateOrderInfo;
    }
}
